/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gt.entity.GtCountry;
import com.thinkgem.jeesite.modules.gt.entity.GtCountryInfo;
import com.thinkgem.jeesite.modules.gt.service.GtCountryInfoService;
import com.thinkgem.jeesite.modules.gt.service.GtCountryService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 科技下乡信息Controller
 * @author zad
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/gtCountryInfo")
public class GtCountryInfoController extends BaseController {

	@Autowired
	private GtCountryInfoService gtCountryInfoService;
	@Autowired
	private GtCountryService gtCountryService;
	@Autowired
	private AreaService areaService;
	
	@ModelAttribute
	public GtCountryInfo get(@RequestParam(required=false) String id) {
		GtCountryInfo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = gtCountryInfoService.get(id);
		}
		if (entity == null){
			entity = new GtCountryInfo();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(GtCountryInfo gtCountryInfo,String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		this.areaService.fetchRegions(model);
		if(null == gtCountryInfo.getArea() || StringUtils.isBlank(gtCountryInfo.getArea().getCode()))
		{
			Area area = UserUtils.getUser().getArea();
			gtCountryInfo.setArea(area);
		}
		
		Page<GtCountryInfo> page = gtCountryInfoService.findPage(new Page<GtCountryInfo>(request, response), gtCountryInfo); 
		model.addAttribute("page", page);
		
		model.addAttribute("gtCountryInfo", gtCountryInfo);
		model.addAttribute("menuId", menuId);
		
		return "modules/gt/basic/gtCountryInfoList";
	}
	
	/**
     * 导出文件
     */
    @RequestMapping("downLoad")
    public void downLoad(String areaId,GtCountry gtCountry,String timeStamp, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
    	Area area = null;
    	if("undefined".equals(areaId))
    	{
    		areaId = "";
    	}
    	if(!StringUtils.isEmpty(areaId))
		{
			area = this.areaService.get(areaId);
		}
    	
    	response.setCharacterEncoding("utf-8");
    	String fileName = UserUtils.getUser().getArea().getName() + Global.getConfig("exportCountryInfoFileName");
    	
    	if(null != area)
    	{
    		fileName = area.getName() + Global.getConfig("exportCountryInfoFileName");
    	}
    	
    	fileName += DateUtils.getDate();
        // fileName = URLEncoder.encode(fileName, "UTF-8");
    	
    	// response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        
        SXSSFWorkbook wb = new SXSSFWorkbook(-1);
        // turn off auto-flushing and accumulate all rows in memory  
        wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用  
        Sheet sh = wb.createSheet("科技下乡扶贫信息");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        try { //从数据库中得到结果  
        	
        	
        	
        	//9c65bfefb542491a89dc2aa8723e60ff
        	GtCountryInfo gtCountryInfo = new GtCountryInfo();
        	if(null == gtCountryInfo.getArea() || StringUtils.isBlank(gtCountryInfo.getArea().getCode()))
    		{
        		if(StringUtils.isEmpty(areaId))
        		{
	    			area = UserUtils.getUser().getArea();
	    			gtCountryInfo.setArea(area);
        		}
        		else
        		{
        			gtCountryInfo.setArea(area);
        		}
    		}
        	gtCountry.setCountryInfo(gtCountryInfo);
        	
        	Page<GtCountry> page = new Page<GtCountry>();
        	page.setOrderBy("b.create_date,b.id,a.update_date");
        	gtCountry.setPage(page);
        	
        	
        	
            List<GtCountry> list = this.gtCountryService.findList(gtCountry);
            
            if(null == list || list.size() < 1)
            {
	            sh.setColumnWidth(0, 50 * 256);
	        	Row rowHeader = sh.createRow(0);
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("信息提示");
	            
	            Row row = sh.createRow(1);
	            Cell cell = row.createCell(0);  
	            cell.setCellValue("没有找到相关条件的数据。");  
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
            }else
            {
	            
	            //设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度  
	            sh.setColumnWidth(0, 5 * 256);
	            sh.setColumnWidth(1, 14 * 256);
	            sh.setColumnWidth(2, 50 * 256);
	            sh.setColumnWidth(3, 12 * 256);
	            sh.setColumnWidth(4, 10 * 256);
	            sh.setColumnWidth(5, 15 * 256);
	            sh.setColumnWidth(6, 30 * 256);
	            Row rowHeader = sh.createRow(0);
	            /*CellStyle headerStyle = rowHeader.getRowStyle();
	            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);*/
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("序号");
	            cellHeader = rowHeader.createCell(1);
	            cellHeader.setCellValue("科技下乡单位");
	            cellHeader = rowHeader.createCell(2);
	            cellHeader.setCellValue("科技下乡内容");
	            cellHeader = rowHeader.createCell(3);
	            cellHeader.setCellValue("重点村总数");
	            cellHeader = rowHeader.createCell(4);
	            cellHeader.setCellValue("联系人");
	            cellHeader = rowHeader.createCell(5);
	            cellHeader.setCellValue("联系方式");
	            cellHeader = rowHeader.createCell(6);
	            cellHeader.setCellValue("扶贫重点村名称");
	            
	            // 只取5000条数据
	            /*if(null != list && list.size() > Constant.Join.JOIN_EXPORT_MOST_ROWS)
	            {
	            	list.subList(Constant.Join.JOIN_EXPORT_MOST_ROWS, list.size()).clear();
	            }*/
	            
	            // 记录本次科技下乡信息id，用于区分是不是同一个科技下乡信息
	            String nowCountryInfoId = null;
	            // 本次科技下乡信息合并单元格开始行数，默认为0；
	            int nowCountryInfoBeginRow = 0;
	            // 序号
	            int seq = 1;
	            int size = list.size();
	            for(int i = 0; i < size; i++) {
	            	
	            	// 当前科技下乡
	            	GtCountry country = list.get(i);
	            	
	            	// 下一个科技下乡
	            	GtCountry countryNext = null;
	            	// 存在下一个，则获取下一个，用于查看本次科技下乡与下一个科技下乡是否是同一个科技下乡
	            	if(i+1 < size)
	            	{
	            		countryNext = list.get(i+1);
	            	}
	            	else
	            	{
	            		countryNext = null;
	            	}
	            	
	            	Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);
	            	
	            	// 第一次初始化本次科技下乡id
	            	if(i == 0)
	            	{
	            		nowCountryInfoId = country.getCountryInfo().getId();
	            		nowCountryInfoBeginRow = 0;
	            		cell.setCellValue(seq);
		                cell = row.createCell(1);
		                cell.setCellValue(country.getCountryInfo().getArea().getName());
		                cell = row.createCell(2);
		                cell.setCellValue(country.getCountryInfo().getContent());  
		                cell = row.createCell(3);
		                cell.setCellValue(null == country.getCountryInfo().getArea().getCountryTotal() ? "":String.valueOf(country.getCountryInfo().getArea().getCountryTotal()));
		                cell = row.createCell(4);
		                cell.setCellValue(country.getCountryInfo().getCreateBy().getOperName());
		                cell = row.createCell(5);
		                cell.setCellValue(country.getCountryInfo().getCreateBy().getMobile());
	            	}
	            	// 判断
	            	else
	            	{
	            		// 上一个科技下乡信息id
	            		String lastCountryInfoId = list.get(i-1).getCountryInfo().getId();
	            		// 本次科技下乡信息id和上次科技下乡信息id不一致，则说明本次是新的科技下乡开始
	            		if(!lastCountryInfoId.equals(country.getCountryInfo().getId()))
	            		{
	            			nowCountryInfoBeginRow = i;
	            			seq ++;
	            			cell.setCellValue(seq);
	    	                cell = row.createCell(1);
	    	                cell.setCellValue(country.getCountryInfo().getArea().getName());
	    	                cell = row.createCell(2);
	    	                cell.setCellValue(country.getCountryInfo().getContent());  
	    	                cell = row.createCell(3);
	    	                cell.setCellValue(null == country.getCountryInfo().getArea().getCountryTotal() ? "":String.valueOf(country.getCountryInfo().getArea().getCountryTotal()));
	    	                cell = row.createCell(4);
	    	                cell.setCellValue(country.getCountryInfo().getCreateBy().getOperName());
	    	                cell = row.createCell(5);
	    	                cell.setCellValue(country.getCountryInfo().getCreateBy().getMobile());
	            		}
	            		
	            	}
	            	
	            	
	                /*Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);
	                cell.setCellValue(seq);
	                cell = row.createCell(1);
	                cell.setCellValue(country.getCountryInfo().getArea().getName());
	                cell = row.createCell(2);
	                cell.setCellValue(country.getCountryInfo().getContent());  
	                cell = row.createCell(3);
	                cell.setCellValue(null == country.getCountryInfo().getArea().getCountryTotal() ? "":String.valueOf(country.getCountryInfo().getArea().getCountryTotal()));
	                cell = row.createCell(4);
	                cell.setCellValue(country.getCountryInfo().getCreateBy().getOperName());
	                cell = row.createCell(5);
	                cell.setCellValue(country.getCountryInfo().getCreateBy().getMobile());*/
	                
	                cell = row.createCell(6);
	                cell.setCellValue(country.getName());
	                
	                
	                // 对比本次科技下乡和下一个科技下乡是否是同一个，
	            	if(i > 0)
	            	{
	            		nowCountryInfoId = country.getCountryInfo().getId();
	            		// 没有下一个科技下乡信息或者下一个科技下乡信息和本次科技下乡信息不是同一个，则开始合并单元格
	            		if(null == countryNext || !nowCountryInfoId.equals(countryNext.getCountryInfo().getId()))
	            		{
	            			for(int col = 0; col < 6; col ++)
	            			{
		            			// 合并单元格，开始行为 nowCountryInfoBeginRow + 1，结束行为i + 1(+1是因为第0行为标题)
		            			CellRangeAddress cellAddr = new CellRangeAddress(nowCountryInfoBeginRow + 1, i + 1, col, col);
		            			sh.addMergedRegion(cellAddr);
	            			}
	            		}
	            	}
	                
	      
	                /*if(i > 0 && (i % 1000 == 0)) {  
	                    ((SXSSFSheet) sh).flushRows();  
	                } */
	            }
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
	            
            }
        } catch(Exception e) {
        	sh.setColumnWidth(0, 50 * 256);
        	Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("信息提示");
            
            Row row = sh.createRow(1);
            Cell cell = row.createCell(0);  
            cell.setCellValue("导出失败，请联系管理员。错误信息：" + e.getMessage());  
            
            e.printStackTrace();
            ((SXSSFSheet) sh).flushRows();
            
            CookieUtils.rememberCookieToken(timeStamp,request,response);
            //统一写出方法
            FileUtils.writeWb(wb,out);
        }  
     // 保存日志
     request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导出了文件：" + fileName);
    }
	
	// 科技下乡扶贫人列表
	@RequestMapping(value = {"listCountry"})
	public String listCountry(GtCountry gtCountry, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		
		Page<GtCountry> page = gtCountryService.findPage(new Page<GtCountry>(request, response), gtCountry); 
		model.addAttribute("page", page);
		gtCountry.setCountryInfo(this.gtCountryInfoService.get(gtCountry.getCountryInfo().getId()));
		model.addAttribute("gtCountry", gtCountry);
		
		return "modules/gt/basic/gtCountryList";
	}

	@RequestMapping(value = "form")
	public String form(GtCountryInfo gtCountryInfo, Model model) {
		
		this.areaService.fetchRegions(model);
		
		model.addAttribute("gtCountryInfo", gtCountryInfo);
		return "modules/gt/basic/gtCountryInfoForm";
	}

	@RequestMapping(value = "formCountry")
	public String formCountry(GtCountry gtCountry, Model model) {
		
		gtCountry.setCountryInfo(this.gtCountryInfoService.get(gtCountry.getCountryInfo().getId()));
		
		List<Dict> helpTypes = DictUtils.getDictList("gt_help_type");
		model.addAttribute("helpTypes", helpTypes);
		
		// 修改时，查询相关信息
		if(StringUtils.isNotBlank(gtCountry.getId()))
		{
			// 记住菜单id
			String menuId = gtCountry.getMenuId();
			gtCountry = this.gtCountryService.get(gtCountry.getId());
			gtCountry.setMenuId(menuId);
		}
		
		model.addAttribute("gtCountry", gtCountry);
		return "modules/gt/basic/gtCountryForm";
	}
	
	@RequestMapping(value = "save")
	public String save(GtCountryInfo gtCountryInfo,String oper,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, gtCountryInfo)){
			return form(gtCountryInfo, model);
		}
		
		Map<String,String> fileRs = FileUtils.writeFile(request, "file", "country");
		if(null != fileRs)
		{
			gtCountryInfo.setFileName(fileRs.get("fileName"));
			gtCountryInfo.setFilePath(fileRs.get("filePath"));
		}
		
		gtCountryInfoService.save(gtCountryInfo);
		addMessage(redirectAttributes, "保存科技下乡信息成功");
		
		
		if(StringUtils.isBlank(gtCountryInfo.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加科技下乡信息:地区，" + gtCountryInfo.getArea().getId()+ gtCountryInfo.getTime());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改科技下乡信息:地区，" + gtCountryInfo.getArea().getId()+ gtCountryInfo.getTime());
		}
		
		
		// 保存后继续到添加页面
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtCountryInfo/form?menuId=" + gtCountryInfo.getMenuId();
		}
		return "redirect:"+super.frontPath+"/gt/gtCountryInfo?menuId=" + gtCountryInfo.getMenuId();
	}
	
	@RequestMapping(value = "saveCountry")
	public String saveCountry(GtCountry gtCountry, String oper,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		

		if(StringUtils.isBlank(gtCountry.getId()))
		{
			// 日志标题
			request.setAttribute("title", "科技下乡：" + gtCountry.getCountryInfo().getId() + "下添加村:" + gtCountry.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改科技下乡信息:" + gtCountry.getName());
		}
		
		
		gtCountryService.save(gtCountry);
		addMessage(redirectAttributes, "保存科技下乡扶贫人成功");
		
		// model.addAttribute("gtCountry", gtCountry);
		// redirectAttributes.addFlashAttribute("gtCountry", gtCountry);
		
		// 保存后继续到添加页面
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtCountryInfo/formCountry/?countryInfo.id=" + gtCountry.getCountryInfo().getId() + "&menuId=" + gtCountry.getMenuId();
		}
		else
		{
			return "redirect:"+super.frontPath+"/gt/gtCountryInfo/listCountry/?countryInfo.id=" + gtCountry.getCountryInfo().getId() + "&menuId=" + gtCountry.getMenuId();
		}
	}
	
	@RequestMapping(value = "delete")
	public String delete(GtCountryInfo gtCountryInfo,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		
		this.gtCountryService.deleteByCountryInfoId(gtCountryInfo.getId());
		
		gtCountryInfoService.delete(gtCountryInfo);
		addMessage(redirectAttributes, "删除科技下乡信息成功");
		
		// 日志标题
		request.setAttribute("title", "删除科技下乡(及其下覆盖人):" + gtCountryInfo.getId());
		
		return "redirect:"+super.frontPath+"/gt/gtCountryInfo?menuId=" + gtCountryInfo.getMenuId();
	}
	
	@RequestMapping(value = "deleteCountry")
	public String deleteCountry(GtCountry gtCountry,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		this.gtCountryService.delete(gtCountry);
		addMessage(redirectAttributes, "删除科技下乡扶贫人成功");
		
		// 日志标题
		request.setAttribute("title", "删除科技下乡扶贫人:" + gtCountry.getId());
		
		return "redirect:"+super.frontPath+"/gt/gtCountryInfo/listCountry?countryInfo.id=" + gtCountry.getCountryInfo().getId() + "&menuId=" + gtCountry.getMenuId();
	}

}